package com.ruoyi.network.service.listener;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.net.NetUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.CellExtra;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.network.domain.entity.IpAddress;
import com.ruoyi.network.domain.entity.IpRange;
import com.ruoyi.network.model.vo.IpAddressImportExcelVO;
import com.ruoyi.network.service.IIpAddressService;
import com.ruoyi.network.service.IIpRangeService;
import com.ruoyi.network.utils.IpRangeUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;

import java.util.*;
import java.util.stream.Collectors;

import static com.ruoyi.network.utils.IpAddressExcelUtil.convertIpAddressExcelVO;

/**
 * 读取IP地址数据 监听器
 *
 * @author Administrator
 */
@Slf4j
public class IpAddressListener implements ReadListener<IpAddressImportExcelVO> {

    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 100;
    /**
     * 数据去重集合
     */
    private Set<String> deduplicateSet = new HashSet<>();
    /**
     * 缓存的数据
     */
    private List<IpAddressImportExcelVO> cachedDataList = new ArrayList<>(BATCH_COUNT);

    public IpAddressListener() {
    }

    @Override
    public void onException(Exception e, AnalysisContext analysisContext) throws Exception {
        // TODO 异常处理
    }

    @Override
    public void invokeHead(Map<Integer, CellData> map, AnalysisContext analysisContext) {

    }

    /**
     * 这个每一条数据解析都会来调用
     *
     * @param data    one row value. Is is same as {@link AnalysisContext#readRowHolder()}
     * @param context 解析上下文
     */
    @Override
    public void invoke(IpAddressImportExcelVO data, AnalysisContext context) {
        log.info("解析到一条数据:{}", JSON.toJSONString(data));

        // 数据校验
        dataValidation(data);

        cachedDataList.add(data);
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            cachedDataList = new ArrayList<>(BATCH_COUNT);
        }
    }

    @Override
    public void extra(CellExtra cellExtra, AnalysisContext analysisContext) {

    }

    /**
     * 所有数据解析完成了 都会来调用
     *
     * @param context 解析上下文
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
        log.info("所有数据解析完成！");
    }

    @Override
    public boolean hasNext(AnalysisContext analysisContext) {
        return false;
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        if (cachedDataList.isEmpty()) {
            log.info("0条数据，开始存储数据库！");
            return;
        }

        int size = cachedDataList.size();
        log.info("{}条数据，开始存储数据库！", size);

        // 获取所有网段信息
        Map<String, List<Long>> map = new HashMap<>();
        for (IpAddressImportExcelVO v : cachedDataList) {
            long ipv4ToLong = NetUtil.ipv4ToLong(v.getIpFormatValue());
            map.computeIfAbsent(v.getRangeName(), k -> new ArrayList<>()).add(ipv4ToLong);
        }
        IIpRangeService rangeService = Optional.ofNullable(SpringUtil.getBean(IIpRangeService.class))
                .orElseThrow(() -> new IllegalStateException("未从容器中找到指定Bean: rangeService"));
        Map<String, IpRange> rangeNames = rangeService.findByRangeNames(map.keySet());

        IIpAddressService ipAddressService = Optional.ofNullable(SpringUtil.getBean(IIpAddressService.class))
                .orElseThrow(() -> new IllegalStateException("未从容器中找到指定Bean: ipAddressService"));
        Map<Long, IpAddress> ipAddressMap = ipAddressService.findByIpValue(map.values().stream().flatMap(Collection::stream).collect(Collectors.toList()));

        List<IpAddress> addressList = convertIpAddressExcelVO(cachedDataList, rangeNames, ipAddressMap);
        if (CollUtil.isNotEmpty(addressList)) {
            ipAddressService.batchInsertion(addressList);
        }
        log.info("存储数据库成功！");
    }

    /**
     * 数据格式校验
     *
     * @param data 待校验数据
     */
    private void dataValidation(IpAddressImportExcelVO data) {
        String rangeName = data.getRangeName();
        String ipFormatValue = data.getIpFormatValue();
        if (Strings.isBlank(data.getRangeName())) {
            throw new ServiceException("IP网段不能为空!");
        }
        if (Strings.isBlank(ipFormatValue)) {
            throw new ServiceException("IP地址不能为空");
        }

        rangeName = rangeName.trim();
        ipFormatValue = ipFormatValue.trim();

        data.setRangeKey(IpRangeUtil.ipRangeNamePreCheck(rangeName));
        data.setRangeName(rangeName);
        data.setIpFormatValue(ipFormatValue);

        if (IpRangeUtil.isValidIpv4(data.getRangeKey())) {
            throw new ServiceException("IP网段格式不正确!");
        }

        if (!deduplicateSet.add(ipFormatValue)) {
            throw new ServiceException("IP地址重复");
        }

        if (IpRangeUtil.isValidIpv4(ipFormatValue)) {
            throw new ServiceException("IP地址格式不正确!");
        }
    }
}